package jmu.cultural_tourism.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DoubaoApiService {

    @Value("${doubao.api.url}")
    private String apiUrl;

    @Value("${doubao.api.token}")
    private String apiToken;

    private final RestTemplate restTemplate;

    public DoubaoApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 调用豆包API（支持文本和图片）
     * @param prompt 文本提示
     * @param imageUrl 图片URL（可选，为null则仅文本交互）
     * @return API响应结果
     */
    public String callDoubaoApi(String prompt, String imageUrl) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiToken);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "doubao-1-5-thinking-vision-pro-250428");

        // 构建消息列表
        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");

        // 构建内容列表（支持文本和图片）
        List<Map<String, Object>> content = new ArrayList<>();

        // 添加文本内容
        Map<String, Object> textContent = new HashMap<>();
        textContent.put("type", "text");
        textContent.put("text", prompt);
        content.add(textContent);

        // 如有图片URL，添加图片内容
        if (imageUrl != null && !imageUrl.isEmpty()) {
            Map<String, Object> imageContent = new HashMap<>();
            imageContent.put("type", "image_url");

            Map<String, String> imageUrlMap = new HashMap<>();
            imageUrlMap.put("url", imageUrl);
            imageContent.put("image_url", imageUrlMap);

            content.add(imageContent);
        }

        message.put("content", content);
        messages.add(message);
        requestBody.put("messages", messages);

        // 创建请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送POST请求
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, requestEntity, Map.class);

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> responseBody = response.getBody();
                if (responseBody != null) {
                    // 解析响应结果（根据实际API响应结构调整）
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                    if (choices != null && !choices.isEmpty()) {
                        Map<String, Object> choice = choices.get(0);
                        Map<String, Object> messageResponse = (Map<String, Object>) choice.get("message");
                        if (messageResponse != null) {
                            return messageResponse.get("content").toString();
                        }
                    }
                    return "API响应格式异常: " + responseBody.toString();
                }
                return "API返回空响应";
            } else {
                return "API调用失败，状态码: " + response.getStatusCodeValue() +
                        "，响应内容: " + response.getBody();
            }
        } catch (Exception e) {
            return "API调用出错: " + e.getMessage();
        }
    }

    public String chatWithDoubao(String prompt) {
        return callDoubaoApi(prompt, null);
    }

    public String chatWithDoubaoAndImage(String prompt, String imageUrl) {
        return callDoubaoApi(prompt, imageUrl);
    }
}
